# -*- coding: utf-8 -*-
import ast
import base64
import hashlib
import json
import sys
import urllib
from collections import OrderedDict

reload(sys)
sys.setdefaultencoding('utf8')
import requests
from django.conf import settings
from pyDes import des, CBC, PAD_PKCS5

from async import async_job
from common.agentpay.base import AbstractHandler
from common.agentpay.db import get_agent_pay_order
from common.channel import admin_db as channel_admin_db
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.types import Enum
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'S20190305164749': {  # dwc 支付宝wap 3% 100---5000
        'syspwd': '647931',
        'deskey': 'Dwwtf3Ze',
        'md5key': 'h1qEL6GC',
        'gateway': 'http://call.vipway01.com/api/pay?params={}&uname={}',
        'query_gateway': 'http://call.vipway01.com/api/pay_check?params={}&uname={}',
        'draw_gateway': 'http://call.vipway01.com/api/draw?params={}&uname={}',
        'draw_query_gateway': 'http://call.vipway01.com/api/draw_check?params={}&uname={}',
        'balance_query_gateway': 'http://call.vipway01.com/api/balance?params={}&uname={}',
    },
}

NOTIFY_PAY_STATUS = Enum({
    "WAIT": (0, u"等待"),
    "SUCCESS": (1, u"成功"),
    "FAIL": (2, u"失败"),
})


def _get_md5_key(mch_id):
    return APP_CONF[mch_id]['md5key']


def _get_des_key(mch_id):
    return APP_CONF[mch_id]['deskey']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_draw_gateway(mch_id):
    return APP_CONF[mch_id]['draw_gateway']


def _get_draw_query_gateway(mch_id):
    return APP_CONF[mch_id]['draw_query_gateway']


def _get_balance_gateway(mch_id):
    return APP_CONF[mch_id]['balance_query_gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_query_agent_pay(mch_id):
    return APP_CONF[mch_id]['query_agent_pay']


def _get_syspwd(mch_id):
    return APP_CONF[mch_id]['syspwd']


def des_encrypt(s, key):
    """
    DES 加密
    :param s: 原始字符串
    :return: 加密后字符串，16进制
    """
    secret_key = key
    iv = secret_key
    k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    en = k.encrypt(s, padmode=PAD_PKCS5)
    return base64.b64encode(en)


def generate_p_syspwd(appid):
    '''  生成下单签名 '''
    s = _get_syspwd(appid) + _get_md5_key(appid)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    return m.hexdigest()


def generate_para_str(d, appid):
    '''  生成下单签名 '''
    s = _get_syspwd(appid) + _get_md5_key(appid)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    md5key = m.hexdigest()
    param = 'p_name={}!p_type={}!p_oid={}!p_money={}!p_url={}!p_surl={}!p_remarks={}!p_syspwd={}'.format(
        d['p_name'], d['p_type'], d['p_oid'], d['p_money'], d['p_url'], d['p_surl'], d['p_remarks'],
        md5key)
    return param


def generate_draw_str(d, appid):
    '''  生成下单签名 '''
    s = _get_syspwd(appid) + _get_md5_key(appid)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    md5key = m.hexdigest()
    param = 'p_name={}!p_type={}!p_oid={}!p_money={}!p_remarks={}!p_syspwd={}!b_type={}!b_id={}!b_code={' \
            '}!b_name={}!b_userid={}!b_phone={}!b_province={}!b_city={}!b_addr={}'.format(
        d['p_name'], d['p_type'], d['p_oid'], d['p_money'], d['p_remarks'], md5key, d['b_type'],
        d['b_id'], d['b_code'], d['b_name'], d['b_userid'], d['b_phone'], d['b_province'], d['b_city'], d['b_addr'])
    return param


def generate_agent_query_str(d, appid):
    '''  生成下单签名 '''
    s = _get_syspwd(appid) + _get_md5_key(appid)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    md5key = m.hexdigest()
    param = 'p_name={}!p_oid={}!p_syspwd={}'.format(
        d['p_name'], d['p_oid'], md5key)
    return param


def generate_agent_balance_query_str(d, appid):
    '''  生成下单签名 '''
    s = _get_syspwd(appid) + _get_md5_key(appid)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    md5key = m.hexdigest()
    param = 'p_name={}!p_type={}!p_syspwd={}'.format(
        d['p_name'], d['p_type'], md5key)
    return param


def generate_query_para(d, app_id):
    '''  生成查询签名 '''
    s = _get_syspwd(app_id) + _get_md5_key(app_id)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    md5key = m.hexdigest()
    param = 'p_name={}!p_oid={}!p_syspwd={}'.format(
        d['p_name'], d['p_oid'], md5key)
    return param


def verify_notify_sign(d, app_id):
    sign = d['p_md5']
    s = app_id + d['p_oid'] + d['p_money'] + _get_syspwd(app_id) + _get_md5_key(app_id)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    calculated_sign = m.hexdigest()
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("peiqipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % d)


# 快捷 WAY_TYPE_BANK_FAST
# 银联扫码 WAY_TYPE_BANK_QR
# 手机微信 WAY_TYPE_WEBCAT_PHONE
# 手机qq WAY_TYPE_QQ_PHONE
# 手机支付宝 WAY_TYPE_ALIPAY_PHONE
# 手机京东 WAY_TYPE_JD_PHONE
# 网银 WAY_TYPE_BANK
# 网银H5 WAY_TYPE_BANK_PHONE
# 微信扫码 WAY_TYPE_WEBCAT
# QQ扫码 WAY_TYPE_QQ
# 支付宝扫码 WAY_TYPE_ALIPAY
# 京东扫码 WAY_TYPE_JD
def _get_paytype(pay_type):
    if pay_type == 'alipay_scan':
        return 'WAY_TYPE_ALIPAY'
    elif pay_type == 'alipay_h5':
        return 'WAY_TYPE_ALIPAY_PHONE'
    elif pay_type == 'wechat_scan':
        return 'WAY_TYPE_WEBCAT'
    elif pay_type == 'wechat_h5':
        return 'WAY_TYPE_WEBCAT_PHONE'
    else:
        return 'WAY_TYPE_ALIPAY'


def _get_bank_type(bank_type):
    if bank_type == 'ICBC':
        return '10001'
    elif bank_type == 'CCB':
        return '10006'
    elif bank_type == 'PNB':
        return '10014'
    elif bank_type == 'BOC':
        return '10004'
    elif bank_type == 'ABC':
        return '10002'
    elif bank_type == 'BCM':
        return '10008'
    elif bank_type == 'CMB':
        return '10003'
    elif bank_type == 'CNCB':
        return '10007'
    elif bank_type == 'CEB':
        return '10010'
    elif bank_type == 'HXB':
        return '10025'
    elif bank_type == 'SPDB':
        return '10015'
    elif bank_type == 'CIB':
        return '10009'
    elif bank_type == 'CMBC':
        return '10006'
    elif bank_type == 'CGB':
        return '10016'
    elif bank_type == 'PSBC':
        return '10012'
    else:
        return 'THIRD_NOT_SUPPORT'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']
    app_id = info['app_id']

    p_dict = OrderedDict((
        ('p_name', app_id),
        ('p_type', _get_paytype(service)),
        ('p_oid', str(pay.id)),
        ('p_money', '%.2f' % pay_amount),
        ('p_bank', ''),
        ('p_url', '{}/pay/api/{}/peiqipay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('p_surl', '{}/pay/api/{}/peiqipay/{}'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('p_remarks', 'charge'),
        ('p_syspwd', generate_p_syspwd(app_id)),
        ('uname', app_id),
    ))
    s = generate_para_str(p_dict, app_id)
    us = urllib.quote(s.encode('utf8'))
    d = des_encrypt(us, _get_des_key(app_id))
    url = _get_gateway(app_id).format(d, app_id)
    _LOGGER.info('peiqipay create_charge data: %s, us is: %s, url is: %s', s, us, url)
    return {'charge_info': url}


# success
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    _LOGGER.info("peiqipay notify data: %s, order_id is: %s", data, data['p_oid'])
    verify_notify_sign(data, app_id)
    pay_id = data['p_oid']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('peiqipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = str(data['p_code'])
    mch_id = pay.mch_id
    trade_no = data.get('p_sid')
    total_fee = float(data['p_money'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('peiqipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    charge_resp = {}
    p_dict = OrderedDict((
        ('p_name', app_id),
        ('p_oid', str(pay_id)),
        ('p_syspwd', generate_p_syspwd(app_id)),
        ('uname', app_id),
    ))
    para = generate_query_para(p_dict, app_id)
    us = urllib.quote(para.encode('utf8'))
    d = des_encrypt(us, _get_des_key(app_id))
    url = _get_query_gateway(app_id).format(d, app_id)
    _LOGGER.info('peiqipay query_charge data is: %s, url is: %s', json.dumps(p_dict), url)
    response = requests.get(url)
    _LOGGER.info('peiqipay query_charge rsp : %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['p_code'])
        # 0:待执行，1:成功，3:失败
        if trade_status == '1':
            trade_no = data.get('p_sid')
            total_fee = float(data['p_money'])
            extend = {
                'trade_status': trade_status,
                'trade_no': trade_no,
                'total_fee': total_fee
            }
            _LOGGER.info('peiqipay query order success, mch_id:%s pay_id:%s',
                         pay_order.mch_id, pay_order.id)
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('peiqipay data error, status_code: %s', response.status_code)


class PeiqiPayHandler(AbstractHandler):

    def submit_order(self, order_no):
        """
        创建代付请求
        :return:
        """
        agent_pay = get_agent_pay_order(order_no)
        chn = channel_admin_db.get_channel(int(agent_pay.channel_id))

        chn_info = json.loads(chn.info)
        app_id = chn_info['app_id']
        service = chn_info['service']

        params = {
            'p_name': app_id,
            'p_type': _get_paytype(service),
            'p_oid': agent_pay.order_no,
            'p_money': '%.2f' % agent_pay.total_fee,
            'p_remarks': 'agent_pay',
            'p_syspwd': generate_p_syspwd(app_id),
            'b_type': _get_bank_type(agent_pay.bank_code),
            'b_id': agent_pay.card_no,
            'b_code': agent_pay.unionpay_no,  # 要去 http://www.eoeit.cn/lianhanghao/index.php 这个网站查出“联行行号”
            'b_name': agent_pay.account_name.encode('utf-8'),
            'b_userid': agent_pay.identity_card,  # 持卡人身份证号 +
            'b_phone': agent_pay.phone_number,  # 银行绑定电话
            'b_province': agent_pay.account_province.encode('utf-8'),  # 银行卡归属省份 +
            'b_city': agent_pay.account_city.encode('utf-8'),  # 银行卡归属城市 +
            'b_addr': agent_pay.bank_name.encode('utf-8'),
        }
        s = generate_draw_str(params, app_id)
        us = urllib.quote(s.encode('utf-8'))
        d = des_encrypt(us, _get_des_key(app_id))
        url = _get_draw_gateway(app_id).format(d, app_id)
        _LOGGER.info('peiqipay draw data: %s, us is: %s, url is: %s', s, us, url)
        response = requests.post(url, timeout=3)
        _LOGGER.info('peiqipay draw rsp status: %s,response: %s', response.status_code, response.text)
        return params['p_oid'], '', response.text

    def query_agent_pay(self, order_no):
        """
        查询代付请求
        :return:
        """
        agent_pay = get_agent_pay_order(order_no)
        chn = channel_admin_db.get_channel(int(agent_pay.channel_id))
        chn_info = json.loads(chn.info)
        app_id = chn_info['app_id']
        params = {
            'p_name': app_id,
            'p_oid': agent_pay.order_no,
            'p_syspwd': generate_p_syspwd(app_id),
        }

        s = generate_agent_query_str(params, app_id)
        us = urllib.quote(s.encode('utf8'))
        d = des_encrypt(us, _get_des_key(app_id))
        url = _get_draw_query_gateway(app_id).format(d, app_id)
        _LOGGER.info('peiqipay agent query data: %s, us is: %s, url is: %s', s, us, url)
        response = requests.post(url, timeout=3)
        _LOGGER.info("peiqi query_agent_pay : %s", response.text.encode('utf8'))
        if response.status_code != 200:
            raise ParamError('peiqipay query_agent_pay error')
        data = json.loads(response.text)
        if data['p_code'] == '0':
            results = '代付处理中->' + str(response.text)
        elif data['status'] == '1':
            results = '代付成功->' + str(response.text)
        else:
            results = '未知状态'
        return results

    def query_balance(self, info):
        info = ast.literal_eval(info.encode("utf-8"))
        service = info['service']
        app_id = info['app_id']
        params = {
            'p_name': app_id,
            'p_type': _get_paytype(service),
            'p_syspwd': generate_p_syspwd(app_id),
        }
        s = generate_agent_balance_query_str(params, app_id)
        us = urllib.quote(s.encode('utf8'))
        d = des_encrypt(us, _get_des_key(app_id))
        url = _get_balance_gateway(app_id).format(d, app_id)
        _LOGGER.info('peiqipay agent balance query data: %s, us is: %s, url is: %s', s, us, url)
        response = requests.post(url, timeout=3)
        _LOGGER.info("peiqi query_agent_pay : %s", response.text.encode('utf8'))
        if response.status_code != 200:
            raise ParamError('peiqipay query_agent_pay error')
        data = json.loads(response.text)
        return data['balance']


handler = PeiqiPayHandler()
